﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Newbie.RabbitMQ
{
    public class RabbitMQSender<T>
    {
        public RabbitMQClientContext Context { get; private set; }

        public IEventMessage<T> Message { get; private set; }

        private RabbitMQSender() { }

        /// <summary>
        /// 消息发送对象
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="message">消息对象</param>
        public RabbitMQSender(RabbitMQClientContext context, IEventMessage<T> message)
        {
            this.Context = context;
            this.Message = message;
        }

        //客户端发送消息的时候要标记上消息的持久化状态
        //可以在创建队列的时候设置此队列是持久化的，但是队列中的消息要在我们发送某个消息的时候打上需要持久化的状态标记。
        public void TriggerEventMessage()
        {
            Context.SendConnection = RabbitMQClientFactory.CreateConnectionForSend();//获取连接
            using (Context.SendConnection)
            {
                //获取发送通道
                Context.SendChannel = RabbitMQClientFactory.CreateModel(Context.SendConnection);

                using (Context.SendChannel)
                {
                    // exclusive 排他队列
                    //Context.SendChannel.QueueDeclare("Q1", true, false, false, null);
                    //Context.SendChannel.ExchangeDeclare("X1", "direct");
                    //Context.SendChannel.QueueBind("Q1", "X1", "K1");
                    //Context.SendChannel.BasicPublish("X1", "K1", null, new byte[2]);
                    //注意：这样Q1才能收到消息



                    //序列化消息器
                    var messageSerializer = MessageSerializerFactory.CreateMessageSerializerInstance();

                    //消息持久化
                    var properties = Context.SendChannel.CreateBasicProperties();
                    properties.DeliveryMode = Message.deliveryMode;
                    properties.ContentType = "text/plain";



                    //推送消息
                    byte[] sMessage = messageSerializer.SerializerBytes(Message);
                    Context.SendChannel.BasicPublish(Context.SendExchange, Context.SendQueueName, properties, sMessage);

                    //Context.SendChannel.BasicPublish("ex.order.topic","order.place.evented",properties,Encoding.UTF8.GetBytes("hello"));
                }
            }
        }
    }
}
